import pymysql
from influxdb import InfluxDBClient


class BaseConnection:
    connection = None

    def __init__(self, host, port, username, password, db=None):
        self.username = username
        self.host = host
        self.port = port
        self.password = password
        self.db = db

    def init(self, host, port, username, password, db=None):
        pass

    @staticmethod
    def get_instance(db_type, host, port, username, password, db):
        """
        :param db_type:
        :return:
        """
        if db_type == 'mysql':
            return MysqlConnection(host, port, username, password, db)
        if db_type == 'influx':
            return InfluxConnection(host,port,username,password,db)


class MysqlConnection(BaseConnection):

    def __init__(self, host, port, username, password, db=None):
        super().__init__(host, port, username, password, db)
        conn = pymysql.Connect(
            host=host,  # 测试环境
            port=int(port),
            user=username, passwd=password,
            db=db, charset='utf8',
            cursorclass=pymysql.cursors.DictCursor)
        self.connection = conn

    def get_conn(self):
        return self.connection


class InfluxConnection(BaseConnection):

    def __init__(self, host, port, username, password, db=None):
        super().__init__(host, port, username, password, db)
        conn = InfluxDBClient(host=host, port=int(port), username=username, password=password,
                              database=db)
        self.connection = conn

    def get_conn(self):
        return self.connection


class ConnectionCache():
    cache_dict = {}

    def get(self, key, db_type,
            host=None, port=None, username=None, password=None, db=None):
        connection = self.cache_dict.get(key, None)
        if connection is None:
            return BaseConnection.get_instance(db_type, host, port, username, password, db)

        return connection


cache = ConnectionCache()
